//
//  PHPhotoLibrary+Ex.m
//  PhotoKit
//
//  Created by Guo Rui on 2017/10/12.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PHPhotoLibrary+Ex.h"
#import "PHAssetCollection+Ex.h"

@implementation PHPhotoLibrary (Ex)

+ (void)createPHAssetCollectionWithTitle:(NSString *)title completion:(void (^)(PHAssetCollection *, NSError *))completion
{
    if (!title || !title.length) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"cn.photo.errordomian" code:0 userInfo:nil];
            completion(nil, error);
        }
        return;
    }
    
    // 1. 判断是否有同名相册
    PHAssetCollection *collection = [PHAssetCollection fetchCustomCollectionWithTitle:title];
    if (collection) {
        if (completion) {
            completion(collection, nil);
        }
        return;
    }
    
    // -- 到达这里表示没有同名相册
    
    // 2. 创建相册
    __block PHAssetCollectionChangeRequest *request = nil;
    __block NSString *localIdentifiers = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        localIdentifiers = request.placeholderForCreatedAssetCollection.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (!error) {
            if (completion) {
                PHFetchOptions *options = [[PHFetchOptions alloc] init];
                completion([PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[localIdentifiers] options:options].firstObject, nil);
            }
        }
        else {
            if (completion) {
                completion(nil, error);
            }
        }
        
    }];
}

+ (PHAssetCollection *)createPHAssetCollectionWithTitle:(NSString *)title error:(NSError *__autoreleasing *)error
{
    if (!title || !title.length) {
        *error = [NSError errorWithDomain:@"cn.photo.errordomian" code:0 userInfo:nil];
        return nil;
    }
    
    // 1. 判断是否有同名相册
    PHAssetCollection *collection = [PHAssetCollection fetchCustomCollectionWithTitle:title];
    if (collection) {
        return collection;
    }
    
    // -- 到达这里表示没有同名相册
    
    // 2. 创建相册
    __block NSString *localIdentifiers = nil;
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        localIdentifiers = request.placeholderForCreatedAssetCollection.localIdentifier;
    } error:error];
    
    if (!(*error)) {
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[localIdentifiers] options:options].firstObject;
    }
    
    return nil;
}



@end
